package com.wentao.mall.api

import com.fasterxml.jackson.databind.ObjectMapper
import com.wentao.mall.dao.UserDao
import com.wentao.mall.entity.Utils
import org.springframework.beans.BeanUtils
import org.springframework.beans.factory.annotation.Value
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.client.RestTemplate
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpSession

@RestController
@RequestMapping("/wx")
class WxController(
    val mapper: ObjectMapper,
    val userDao: UserDao,
    val utils: Utils
) {

    val rest = RestTemplate()

    @Value("\${wx.appid}")
    lateinit var appid: String;

    @Value("\${wx.secret}")
    lateinit var secret: String;

    val reader = mapper.readerFor(WxResp::class.java)
    val url = "https://api.weixin.qq.com/sns/jscode2session?appid={appid}&secret={secret}&js_code={code}&grant_type=authorization_code"

    @RequestMapping("/login", method = [RequestMethod.GET])
    fun wxLogin(code: String,session:HttpSession,request:HttpServletRequest): WxResp {
        val obj = rest.getForObject(url, String::class.java, appid, secret, code)
        println(obj)

        val res = reader.readValue<WxResp>(obj)
        println(res)
        println(res.success)

        if (res.success) {
            val openid = res.openid!!
            val user = userDao.findByOpenid(openid)

            if (user == null) {
                val user1 = User(openid = openid)
                userDao.save(user1)
            }
        }
        val httpSession = request.session



        return res
    }

    @RequestMapping("/user/sync", method = [RequestMethod.POST])
    fun userSync(param:WxUserInfoParam): Result {
        //"15ZC8qjkYgfwR7/axypDWZ9kcKJSKOQ2yflQ6G7/AOllHLpR3U7thA+PR+aFoZ9+niQdtB7U6xVS3vQmU2vSHV9k4W8LsNAgJo7yCtfR91pZk+NI/A/EckX4buiJYJ/dgworJ4fT+dsS0FFyvitrbe8aXNito0nFIRSSoJSuh29rJHHLKt7H8p9u7/agPu9JCDC3zr8jkIBeFD0OWKZjyxqLfcC9i6SD+LYNodMzliD6u7XgD+iwaVn6FDnHFD14AJHVTodlcdeM+5zvlMPtZfJ3Kw0PcTivayM4lT62AByvW7PcLUyMrB5tZIG6SYHq6IIJQ/aI4YT7CkumjgA9izzLx5Pr+/TDdHGdc0xfw1OqI/N3G4yx+d0phLlp+AnZnC0Cfd7j64xhwDdE//CQkCK0lgWW3QPTRrTYaI+WYaDk6BwKlnwzgdxE7lvLK8kBrRqPPpjP6LnFpeVwzw6JqSOCtq/05F8Pd717iQyLLx2K1j6ScavcPCTlq+Ut1G65/hsE2E/EEo5DdFDML4IukQ=="
        val encryptedData = param.encryptedData
        val iv = param.iv
        val sessionKey = ""
        val json = utils.decrypt(encryptedData, sessionKey, iv)

        //{"openId":"oGZUI0egBJY1zhBYw2KhdUfwVJJE","nickName":"Band","gender":1,"language":"zh_CN","city":"Guangzhou","province":"Guangdong","country":"CN","avatarUrl":"http://wx.qlogo.cn/mmopen/vi_32/aSKcBBPpibyKNicHNTMM0qJVh8Kjgiak2AHWr8MHM4WgMEm7GFhsf8OYrySdbvAMvTsw3mo8ibKicsnfN5pRjl1p8HQ/0","unionId":"ocMvos6NjeKLIBqg5Mr9QjxrP1FA","watermark":{"timestamp":1477314187,"appid":"wx4f4bc4dec97d474b"}}
        val user = mapper.readValue<User>(json, User::class.java)
        val openid = user.openid ?: return Result.error("Data have no openId")

        val userFind = userDao.findByOpenid(openid) ?: return Result.error("user not found")



        BeanUtils.copyProperties(user,userFind)
        userDao.save(userFind)

        return Result.success()
    }

    data class WxUserInfoParam(
        val rawData: String? = null,
        val encryptedData: String,
        val signature: String? = null,
        val iv: String,
        val cloudID: String? = null
    )

}

data class WxResp(
    val errcode: String? = null,
    val errmsg: String? = null,

    val session_key: String? = null,
    val expires_in: Int? = null,
    val openid: String? = null
) {
    val success: Boolean = errcode == null
}
